<template>
	<view class="room-detail-container">
		<view v-if="loading" class="loading-container">
			<view class="loading-content">
				<view class="loading-icon">
					<view class="loading-dot"></view>
					<view class="loading-dot"></view>
					<view class="loading-dot"></view>
				</view>
				<view class="loading-text-container">
					<view class="loading-text">数据加载中</view>
					<view class="loading-dots">
						<text>.</text>
						<text>.</text>
						<text>.</text>
					</view>
				</view>
			</view>
		</view>
		<view v-else class="detail-card">
			<view class="card-title">房间详情 - {{ room.id }}</view>
			
			<!-- Detail Items - Controlled by Role -->
			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'dj', 'yewuyuan', 'yewujinli'])" class="detail-item">
				<view class="detail-row">
					<view class="detail-col">
						<text class="label">订房人:</text>
						<picker
							mode="selector"
							:range="userList"
							range-key="nickName"
							@change="onBookerChange"
						>
							<view class="value">{{ selectedBooker.nickName || '请选择订房人' }}</view>
						</picker>
						<input v-model="searchName" placeholder="输入姓名搜索" @input="onSearchUser" />
					</view>
					<view class="detail-col">
						<text class="label">进房次数:</text>
						<text class="value">{{ room.bookerEntryCount }}</text>
					</view>
				</view>
			</view>
			
			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'dj', 'yewuyuan', 'yewujinli'])" class="detail-item">
				<view class="detail-row">
					<view class="detail-col">
						<text class="label">服务员:</text>
						<text class="value">{{ room.serviceStaffName || room.serviceStaffId }}</text>
					</view>
					<view class="detail-col">
						<text class="label">进房次数:</text>
						<text class="value">{{ room.serviceStaffEntryCount }}</text>
					</view>
				</view>
			</view>
			
			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'duchayuanyuan', 'dj', 'yewuyuan', 'yewujinli'])" class="detail-item">
				<text class="label">DJ:</text>
				<text class="value">{{ room.djName || room.djId }}</text>
			</view>

			<!-- 新增静态信息 -->
			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'yewuyuan', 'yewujinli'])" class="detail-item">
				<text class="label">优秀业务员:</text>
				<text class="value">暂无</text>
			</view>

			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'yewuyuan', 'yewujinli'])" class="detail-item">
				<text class="label">投诉情况:</text>
				<text class="value">暂无投诉</text>
			</view>

			

			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'duchayuan', 'dj', 'yewuyuan', 'yewujinli'])" class="detail-item">
				<text class="label">业务员:</text>
				<view class="value-with-button">
					<button class="scan-btn" @click="scanCode">扫一扫</button>
				</view>
			</view>

			<!-- 业务员列表 -->
			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'duchayuan', 'dj', 'yewuyuan', 'yewujinli'])" class="salesperson-list">
				<view class="list-title">业务员列表</view>
				<view class="list-content">
					<view class="salesperson-item" v-for="(item, index) in room.salespersonList" :key="index">
						<text class="salesperson-id">{{ item.id }}</text>
						<text class="salesperson-name">{{ item.name }}</text>
						<text class="salesperson-level">{{ item.level }}</text>
					</view>
				</view>
			</view>

			<!-- 买单情况 -->
			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'duchayuan', 'yewuyuan', 'yewujinli'])" class="detail-section-title">买单情况</view>
			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'duchayuan', 'yewuyuan', 'yewujinli'])" class="detail-item">
				<text class="label">账单:</text>
				<text class="value">{{ room.totalAmount }}</text>
			</view>
			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'duchayuan', 'yewuyuan', 'yewujinli'])" class="detail-item">
				<text class="label">打折:</text>
				<text class="value">{{ room.discount }}</text>
			</view>
			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'duchayuan', 'yewuyuan', 'yewujinli'])" class="detail-item">
				<text class="label">服务员工资:</text>
				<text class="value">{{ room.serviceStaffPayment }}</text>
			</view>
			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'duchayuan', 'yewuyuan', 'yewujinli'])" class="detail-item">
				<text class="label">DJ工资:</text>
				<text class="value">{{ room.djPayment }}</text>
			</view>
			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'duchayuan', 'yewuyuan', 'yewujinli'])" class="detail-item">
				<text class="label">业务员工资:</text>
				<text class="value">{{ room.salespersonPayment }}</text>
			</view>
			<view v-if="hasRole('admin') || hasAnyRole(['yewujinli'])" class="detail-item">
				<button class="scan-btn" @click="scanCode">呼叫发台</button>
			</view>
			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'duchayuan', 'yewuyuan', 'yewujinli'])" class="detail-section-title">巡查情况</view>

			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'duchayuan', 'yewuyuan', 'yewujinli'])" class="detail-item">
				<text class="label">拍照:</text>
				<text class="value">待处理</text>
			</view>

			<view v-if="hasRole('admin') || hasAnyRole(['guanliceng', 'duchayuan', 'yewuyuan', 'yewujinli'])" class="detail-item">
				<text class="label">问题:</text>
				<text class="value">无</text>
			</view>
		</view>
	</view>
</template>

<script>
	import { getToken } from '@/utils/auth'
	import { getRoom } from '@/api/system/room'
	import { getUser, listUser } from '@/api/system/user'
	import { addSalespersonToRoomGroup } from '@/api/system/room'
	

	export default {
		data() {
			return {
				room: {},
				salespersonList: [], // 将从groupName中解析
				roles: [], // 存储用户角色
				loading: false, // 添加loading状态
				userList: [],
				selectedBooker: {},
				searchName: ''
			}
		},
		onLoad(options) {
			// 获取用户信息和角色
			const userInfo = uni.getStorageSync('userInfo');
			if (userInfo) {
				this.roles = userInfo.roles || [];
			} else if (getToken()) {
				console.warn('用户信息未在本地存储找到，请确保登录时已正确存储。');
			}

			// 获取房间信息
			if (options.room) {
				const roomData = JSON.parse(decodeURIComponent(options.room));
				this.getRoomDetail(roomData.id);
				uni.setNavigationBarTitle({
					title: `房间详情 - ${roomData.id}`
				});
			} else {
				this.$modal.msgError('未获取到房间信息');
			}

			this.getUserList();
		},
		methods: {
			// 获取房间详情
			async getRoomDetail(id) {
				this.loading = true; // 开始加载
				try {
					const res = await getRoom(id);
					if (res.code === 200) {
						this.room = {
							...res.data,
							// 直接使用后端返回的用户名信息
							bookerName: res.data.bookerName,
							serviceStaffName: res.data.serviceStaffName,
							djName: res.data.djName,
							// 解析业务员列表
							salespersonList: await this.parseSalespersonList(res.data.groupNameList)
						};
					} else {
						this.$modal.msgError(res.msg || '获取房间详情失败');
					}
				} catch (error) {
					this.$modal.msgError('获取房间详情失败');
				} finally {
					this.loading = false; // 结束加载
				}
			},
			// 解析业务员列表
			async parseSalespersonList(groupNameList) {
				if (!groupNameList || !Array.isArray(groupNameList)) return [];
				
				return groupNameList.map(user => ({
					id: user.userId,
					name: user.userName,
					level: user.level || '无'
				}));
			},
			async scanCode() {
				// #ifdef MP
				uni.scanCode({
					scanType: ['qrCode'], // 只扫描二维码
					success: async (res) => {
						this.handleScanResult(res.result);
					},
					fail: (err) => {
						console.error('扫码失败：', err);
						this.$modal.msgError('扫码失败');
					}
				});
				// #endif

				// #ifdef H5 || APP-PLUS
				this.$modal.msgError('扫码功能仅支持小程序环境');
				// #endif
			},

			// 处理扫码结果
			async handleScanResult(result) {
				console.log('扫码结果：', result);
				try {
					// 尝试解析JSON
					const qrData = JSON.parse(result);
					if (qrData && qrData.userId) {
						const userId = qrData.userId;
						
						// 检查是否已经在列表中
						const existingSalesperson = this.room.salespersonList.find(item => item.id === userId);
						if (existingSalesperson) {
							this.$modal.msgError('该业务员已在列表中');
							return;
						}
						
						try {
							// 获取业务员信息
							console.log('开始获取业务员信息，userId:', userId);
							const userRes = await getUser(userId);
							console.log('获取业务员信息响应:', userRes);
							if (userRes.code === 200) {
								const salesperson = userRes.data;
								// 显示确认对话框
								uni.showModal({
									title: '添加业务员',
									content: `是否将业务员 ${salesperson.userName} 添加到预定业务员组？`,
									success: async (modalRes) => {
										if (modalRes.confirm) {
											try {
												// 调用后端API添加业务员到房间组
												const addRes = await addSalespersonToRoomGroup({
													roomId: this.room.id,
													salespersonUserId: userId
												});
												if (addRes.code === 200) {
													this.$modal.msgSuccess('添加成功');
													// 刷新房间详情
													await this.getRoomDetail(this.room.id);
												} else {
													console.error('添加业务员失败，响应:', addRes);
													// 显示具体的错误信息
													this.$modal.msgError(addRes.msg || '添加失败');
													// 如果是EE限制的错误，显示更友好的提示
													if (addRes.msg && addRes.msg.includes('只能加入一个房间')) {
														this.$modal.msgError('该业务员已被限制只能加入一个房间');
													}
												}
											} catch (error) {
												console.error('添加业务员失败，错误详情:', error);
												this.$modal.msgError('添加失败，请重试');
											}
										}
									}
								});
							} else {
								console.error('获取业务员信息失败，响应码:', userRes.code, '响应信息:', userRes.msg);
								this.$modal.msgError('获取业务员信息失败');
							}
						} catch (error) {
							console.error('获取业务员信息失败，错误详情:', error);
							this.$modal.msgError('获取业务员信息失败');
						}
					} else {
						console.error('无效的二维码数据:', qrData);
						this.$modal.msgError('无效的业务员二维码');
					}
				} catch (error) {
					console.error('解析二维码数据失败:', error);
					this.$modal.msgError('无效的业务员二维码');
				}
			},
			// 检查用户是否包含某个角色
			hasRole(role) {
				return this.roles.includes(role);
			},
			// 检查用户是否包含任一指定角色
			hasAnyRole(roles) {
				return roles.some(role => this.roles.includes(role));
			},
			// 搜索用户
			onSearchUser() {
				this.getUserList(this.searchName);
			},
			// 获取用户列表
			getUserList(name = '') {
				listUser({ nickName: name }).then(res => {
					this.userList = res.rows || res.data || [];
				});
			},
			// 选择订房人
			onBookerChange(e) {
				this.selectedBooker = this.userList[e.detail.value];
				// 你可以把bookerId等赋值到room对象
				// this.room.bookerId = this.selectedBooker.userId;
				// this.room.bookerName = this.selectedBooker.nickName;
			}
		}
	}
</script>

<style lang="scss" scoped>
.room-detail-container {
	min-height: 100vh;
	background-color: #f5f7fa;
	padding: 30rpx;
}

.detail-card {
	background: #fff;
	border-radius: 16rpx;
	padding: 40rpx;
	box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);

	.card-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		text-align: center;
	}

	.detail-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #eee;

		&:last-child {
			border-bottom: none;
		}

		.detail-row {
			display: flex;
			width: 100%;
			gap: 40rpx;
		}

		.detail-col {
			flex: 1;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.label {
				font-size: 30rpx;
				color: #666;
				flex-basis: 160rpx;
				margin-right: 30rpx;
			}

			.value {
				font-size: 30rpx;
				color: #333;
				flex: 1;
				text-align: right;
				word-break: break-word;
			}
		}
	}

	.value-with-button {
		display: flex;
		align-items: center;
		gap: 20rpx;
		flex: 1;
		justify-content: flex-end;
	}

	.scan-btn {
		margin: 0;
		padding: 0 20rpx;
		height: 60rpx;
		line-height: 60rpx;
		font-size: 24rpx;
		background-color: #007AFF;
		color: #fff;
		border-radius: 30rpx;
	}

	.salesperson-list {
		margin-top: 30rpx;
		background: #fff;
		border-radius: 16rpx;
		padding: 30rpx;

		.list-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 20rpx;
		}

		.list-content {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;
		}

		.salesperson-item {
			background: #f5f7fa;
			padding: 10rpx 20rpx;
			border-radius: 8rpx;
			font-size: 28rpx;

			.salesperson-id {
				color: #666;
				margin-right: 10rpx;
			}

			.salesperson-name {
				color: #333;
				margin-right: 10rpx;
			}

			.salesperson-level {
				color: #007AFF;
				font-weight: bold;
			}
		}
	}

	.detail-section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-top: 40rpx;
		margin-bottom: 20rpx;
		padding-bottom: 10rpx;
		border-bottom: 2rpx solid #eee;
	}

	.loading-container {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: rgba(245, 247, 250, 0.95);
		z-index: 999;

		.loading-content {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 60rpx;
			background: #ffffff;
			border-radius: 24rpx;
			box-shadow: 0 12rpx 48rpx rgba(0, 0, 0, 0.15);
			transform: translateY(-40rpx);
		}

		.loading-icon {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 40rpx;
			width: 160rpx;
			height: 160rpx;
			position: relative;
		}

		.loading-dot {
			position: absolute;
			width: 40rpx;
			height: 40rpx;
			border-radius: 50%;
			background: #007AFF;
			animation: bounce 1.4s infinite ease-in-out both;

			&:nth-child(1) {
				left: 0;
				animation-delay: -0.32s;
			}

			&:nth-child(2) {
				left: 50%;
				transform: translateX(-50%);
				animation-delay: -0.16s;
			}

			&:nth-child(3) {
				right: 0;
			}
		}

		.loading-text-container {
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.loading-text {
			font-size: 36rpx;
			font-weight: 600;
			color: #333;
			margin-right: 8rpx;
		}

		.loading-dots {
			display: flex;
			align-items: center;
			height: 36rpx;

			text {
				font-size: 36rpx;
				font-weight: 600;
				color: #007AFF;
				animation: dots 1.4s infinite ease-in-out both;

				&:nth-child(1) {
					animation-delay: -0.32s;
				}

				&:nth-child(2) {
					animation-delay: -0.16s;
				}
			}
		}
	}

	@keyframes bounce {
		0%, 80%, 100% {
			transform: scale(0);
			opacity: 0.5;
		}
		40% {
			transform: scale(1);
			opacity: 1;
		}
	}

	@keyframes dots {
		0%, 80%, 100% {
			opacity: 0.2;
			transform: translateY(0);
		}
		40% {
			opacity: 1;
			transform: translateY(-10rpx);
		}
	}
}
</style>
